package com.appbee.gdata.youtube.client.presenter;

import java.util.List;

import javax.inject.Inject;

import com.appbee.core.client.jsni.JsArrayConverter;
import com.appbee.gdata.youtube.client.search.Entry;
import com.appbee.gdata.youtube.client.search.Feed;
import com.appbee.gdata.youtube.client.search.FeedCallback;
import com.appbee.gdata.youtube.client.search.FeedResult;
import com.appbee.gdata.youtube.client.search.YoutubeFilter;
import com.appbee.gdata.youtube.client.search.YoutubeService;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.user.client.Window;

public class SearchPresenter
{
	public interface FilterView
	{
		public String getValue();

		public void setValue(String value);
	}
	
	public interface ListView
	{
		public void showEntryList(List<Entry> list);

		public void clearEntryList();
	}

	private YoutubeService service;
	private FilterView filterView;
	private ListView listView;
	private String currentValue = "";

	@Inject
	public SearchPresenter(YoutubeService service)
	{
		this.service = service;
	}

	public void setFilterView(FilterView filterView)
	{
		this.filterView = filterView;
	}
	
	public void setListView(ListView listView)
	{
		this.listView = listView;
	}

	public void onKeyDown(int keyCode)
	{
		if (keyCode == KeyCodes.KEY_ENTER)// Enter
		{
			currentValue = filterView.getValue();
			if (currentValue.length() == 0)
			{
				listView.clearEntryList();
				return;
			}
			YoutubeFilter filter = new YoutubeFilter();
			filter.setQuery(currentValue);
			service.findByFilter(filter, new FeedCallback()
			{

				@Override
				public void onSuccess(FeedResult feedResult)
				{
					Feed feed = feedResult.getFeed();
					listView.showEntryList(JsArrayConverter.toList(feed.getEntry()));

				}

				@Override
				public void onFailure(Throwable caught)
				{
					Window.alert(caught.getMessage());

				}
			});
		}
		else if (filterView.getValue().length() == 0)
		{
			currentValue = filterView.getValue();
			listView.clearEntryList();
			return;
		}

	}

}
